package com.cheng.io;

import cn.hutool.json.JSONUtil;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author yangcheng
 * @version 1.0
 * @date 2021-07-04 21:38
 * @description 一般用于调用其他服务，请求类型GET,PUT,POST,DELETE
 * <p>
 * 使用流程
 * 创建 CloseableHttpClient对象或CloseableHttpAsyncClient对象，前者同步，后者为异步
 * 创建Http请求对象
 * 调用execute方法执行请求，如果是异步请求在执行之前需调用start方法
 */
public class HttpClientTest {


    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    public String base_url = "http://localhost:8801";

    /**
     * get 请求，常用于获取请求
     *
     * @param api
     */
    public void testGet(String api) throws IOException {
        HttpGet httpGet = new HttpGet(base_url + api);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
     * put 请求,常用于更新请求
     *
     * @param api
     */
    public void testPut(String api) throws IOException {
        HttpPut httpPut = new HttpPut(base_url + api);
        TestModel testModel=new TestModel();
        httpPut.setHeader("Content-Type", "application/json;charset=utf8");
        httpPut.setEntity(new StringEntity(JSONUtil.toJsonStr(testModel)));
        CloseableHttpResponse response = httpClient.execute(httpPut);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
     * POST 请求,常用于新增或复杂的获取请求
     *
     * @param api
     */
    public void testPost(String api) throws IOException {
        HttpPost httpPost = new HttpPost(base_url + api);
        TestModel testModel=new TestModel();
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        httpPost.setEntity(new StringEntity(JSONUtil.toJsonStr(testModel)));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
     * DELETE 请求,常用于删除请求
     *
     * @param api
     */
    public void testDelete(String api) throws IOException {
        HttpDelete httpDelete = new HttpDelete(base_url + api);
        httpDelete.setHeader("Content-Type", "application/json;charset=utf8");
        CloseableHttpResponse response = httpClient.execute(httpDelete);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    private class TestModel {
        private Integer testVo;
    }

}
